<?php
/*
Plugin Name: MG Format Cleanup
Plugin URI: http://www.bymg.com/
Description: 在复制其它文章的时候，常常发现需要清理很多格式以及链接。本插件则提供自动清理的功能。
Version: 0.0.3
Author: Mike Gaul
Author URI: http://www.bymg.com
*/

if(preg_match('#' . basename(__FILE__) . '#', $_SERVER['PHP_SELF'])) { die('You are not allowed to call this page directly.'); }

if(!defined('MG_TBKP_ABSPATH')) define('MG_TBKP_ABSPATH', ABSPATH . 'wp-content/plugins/mg-taobaoke-pages' );

$mg_format_clean = new mgPlugin_Format_Clean();

if (is_admin()) {
	add_action('admin_menu', array($mg_format_clean, 'add_custom_box_sidebox'));
	add_action('content_save_pre', array($mg_format_clean, 'cleanup'));
}

class mgPlugin_Format_Clean {
    
    var $actions = array(
        0 => '清理显示格式',
        1 => '清理链接',
        2 => '下载远程图片',
//        3 => '清理空格',
    );
    
    var $valid_extensions = array('jpg', 'png', 'gif', 'jpeg');
    
    function mgPlugin_Format_Clean () {
        
    }
    
    function add_custom_box_sidebox()
    {
    	if (function_exists('add_meta_box')) {
    		add_meta_box('mg-fc-setting', '清理文章格式', array($this, 'custom_sidebox'), 'post', 'side', 'low');
    	}
    }
    
    function custom_sidebox()
    {
        foreach ($this->actions as $key => $val) {
    	    echo "<p><label><input type=\"checkbox\" name=\"mg_fc_type[]\" value=\"{$key}\" />{$val}</label></p>\n";
        }
    }
    
    function cleanup($content)
    {
        if (empty($_POST['mg_fc_type']) || !is_array($_POST['mg_fc_type'])) {
        	return $content;
        }
        
    	// mg_fc_type值有0时，清理显示格式
    	if (in_array(0, $_POST['mg_fc_type'])) {
    	    $content = $this->__cleanup_format($content);
    	}
    	
    	// mg_fc_type值有1时，清理链接
    	if (in_array(1, $_POST['mg_fc_type'])) {
    		$content = $this->__cleanup_links($content);
    	}
    	
    	// mg_fc_type值有2时，下载非站内的远程图片
    	if (in_array(2, $_POST['mg_fc_type'])) {
    		$content = $this->__download_remote_images($content);
    	}
    	
    	// mg_fc_type值有3时，清理空格
    	if (in_array(3, $_POST['mg_fc_type'])) {
    		$content = $this->__cleanup_blank($content);
    	}
    	
    	return $content;
    }
    
    function __cleanup_links($content)
    {
		$content = preg_replace('/<a[^>]*?>/', '', $content);
		$content = str_replace('</a>', '', $content);
		
        return $content;	
    }
    
    function __cleanup_format($content)
    {
        $content = stripslashes($content);
        
		$content = preg_replace('/<img[\s\S]+?src=[\'"](.+?)[\'"][\s\S]*?>/', '<img src="$1" />', $content);
		$content = preg_replace('/<\/img[^>]*?>/', '', $content);
		
		$content = preg_replace('/<div[^>]*?>/', '<p>', $content);
		$content = preg_replace('/<\/div>[^>]*?/', '</p>', $content);
		
		$content = preg_replace('/<p[^>]*?>/', '<p>', $content);
		$content = preg_replace('/<\/p[^>]*?>/', '</p>', $content);
		
		$content = preg_replace('/<span[^>]*?>/', '', $content);
		$content = preg_replace('/<\/span[^>]*?>/', '', $content);
		
		$content = preg_replace('/<strong[^>]*?>/', '', $content);
		$content = preg_replace('/<\/strong[^>]*?>/', '', $content);
		
		$content = preg_replace('/<b[^>]*?>/', '', $content);
		$content = preg_replace('/<\/b[^>]*?>/', '', $content);
		
		$content = preg_replace('/<ul[^>]*?>/', '<ul>', $content);
		$content = preg_replace('/<\/ul[^>]*?>/', '</ul>', $content);
		
		$content = preg_replace('/<li[^>]*?>/', '<li>', $content);
		$content = preg_replace('/<\/li[^>]*?>/', '</li>', $content);
		
		return $content;
    }
    
    function __cleanup_blank($content)
    {
		$content = preg_replace('/([\x{4e00}-\x{9fa5}]+?)(&nbsp;| )([\x{4e00}-\x{9fa5}]+?)/', '$1$3', $content);
		
		return $content;
    }
    
    function __download_remote_images($content)
    {
        $content = stripslashes($content);
    	preg_match_all('/<img[\s\S]+?src=[\'"](.+?)[\'"][\s\S]*?>/', $content, $matches);
    	
    	$wp_upload_dir = wp_upload_dir();
    	if ($wp_upload_dir['error']) return $content;
    	
        $old_img_tags = $matches[0]; // 旧图片的标签代码，准备用来替换
        $old_img_srcs = $matches[1]; // 旧图片的网址
        
        foreach ($old_img_srcs as $index => $src) {
        	if ($new_img_src = $this->__save_remote_image($src, $wp_upload_dir)) {
        	    $new_img_tag = "<img src=\"{$new_img_src}\" />";
        		$content = str_replace($old_img_tags[$index], $new_img_tag, $content);
        	}
        }
        
        return $content;
    }
    
    function __save_remote_image($src, $wp_upload_dir)
    {
        global $post;
        
        // 如果是本站点内部文件，则不下载
        $pattern = '^'.get_option("siteurl");
        $pattern = str_replace('/', '\/', $pattern);
        $pattern = str_replace('.', '\.', $pattern);
        if (preg_match('/'.$pattern.'/', $src)) {
        	return false;
        }
        
        $imginfo = pathinfo($src);
        
        // 如果不是有效扩展名，则不下载
        if (!in_array($imginfo['extension'], $this->valid_extensions)) {
        	return false;
        }
        
        if ($imginfo['basename']) {
        	$new_filename = substr(md5($src),0,4)."_".$imginfo['basename'];
        }else {
            $new_filename = substr(md5($src),0,5).".".$imginfo["extension"];
        }
        
    	$new_src  = $wp_upload_dir["url"].'/'.$new_filename;
    	$new_path = $wp_upload_dir['path'].'/'.$new_filename;
    	
    	if (file_exists($new_path)) { // 文件存在则说明已经下载过了
    	    return $new_src;
    	}else {
    	    $imgdata = @file_get_contents($src);
    	    if ($imgdata) {
    	    	if (@file_put_contents($new_path, $imgdata)) {
    	    	    $size = getimagesize($new_path);
    	    	    
            		$attachment = array(
                        'post_mime_type' => $size['mime'],
                        'guid'           => $new_src,
                        'post_parent'    => $post->ID,
                        'post_title'     => $new_filename,
                        'post_content'   => $new_filename,
                        'post_author'	 => $post->post_author,
            		);
            		
            		// 作为附件加入到数据库中
            		$id = wp_insert_attachment($attachment, $new_path, $post->ID);
            		if (!is_wp_error($id)) 
            		{
                        @include_once(ABSPATH.'/wp-admin/includes/image.php');
                        wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $new_path));
            		}
    	    	}
    	    	return $new_src;
    	    }else {
    	    	return false;
    	    }
    	}
    	
    	return false;
    }
}